1. Module (chicken irregex)
    1. Procedures
      1. irregex
      2. string->irregex
      3. sre->irregex
      4. string->sre
      5. maybe-string->sre
      6. glob->sre
      7. irregex?
      8. irregex-search
      9. irregex-match
      10. irregex-match?
      11. irregex-match-data?
      12. irregex-num-submatches
      13. irregex-match-num-submatches
      14. irregex-names
      15. irregex-match-names
      16. irregex-match-valid-index?
      17. irregex-match-substring
      18. irregex-match-start-index
      19. irregex-match-end-index
      20. irregex-match-subchunk
      21. irregex-match-start-chunk
      22. irregex-match-end-chunk
      23. irregex-replace
      24. irregex-replace/all
      25. irregex-split
      26. irregex-extract
      27. irregex-fold
    2. Extended SRE Syntax
      1. Basic SRE Patterns
      2. SRE Repetition Patterns
      3. SRE Character Sets
      4. SRE Assertion Patterns
      5. SRE Utility Patterns
    3. Supported PCRE Syntax
    4. Chunked String Matching
      1. make-irregex-chunker
      2. irregex-search/chunked
      3. irregex-match/chunked
      4. irregex-fold/chunked
    5. Utilities
      1. irregex-quote
      2. irregex-opt
      3. sre->string

Module (chicken irregex)

This module provides support for regular expressions, using the powerful irregex regular expression engine by Alex Shinn. It supports both POSIX syntax with various (irregular) PCRE extensions, as well as SCSH's SRE syntax, with various aliases for commonly used patterns. DFA matching is used when possible, otherwise a closure-compiled NFA approach is used. Matching may be performed over standard Scheme strings, or over arbitrarily chunked streams of strings.

On systems that support dynamic loading, the irregex module can be made available in the CHICKEN interpreter (csi) by entering

(import (chicken irregex))

Procedures

irregex

string->irregex

sre->irregex

[procedure] (irregex <posix-string-or-sre> [<options> ...])
[procedure] (string->irregex <posix-string> [<options> ...])
[procedure] (sre->irregex <sre> [<options> ...])

Compiles a regular expression from either a POSIX-style regular expression string (with most PCRE extensions) or an SCSH-style SRE. There is no (rx ...) syntax - just use normal Scheme lists, with quasiquote if you like.

Technically a string by itself could be considered a valid (though rather silly) SRE, so if you want to just match a literal string you should use something like (irregex `(: ,str)), or use the explicit (sre->irregex str).

The options are a list of any of the following symbols:

'i, 'case-insensitive
match case-insensitively
'm, 'multi-line
treat string as multiple lines (effects ^ and $)
's, 'single-line
treat string as a single line (. can match newline)
'utf8
utf8-mode (assumes strings are byte-strings)
'fast
try to optimize the regular expression
'small
try to compile a smaller regular expression
'backtrack
enforce a backtracking implementation

The 'fast and 'small options are heuristic guidelines and will not necessarily make the compiled expression faster or smaller.

string->sre

maybe-string->sre

[procedure] (string->sre <str>)
[procedure] (maybe-string->sre <obj>)

For backwards compatibility, procedures to convert a POSIX string into an SRE.

maybe-string->sre does the same thing, but only if the argument is a string, otherwise it assumes <obj> is an SRE and returns it as-is. This is useful when you want to provide an API that allows either a POSIX string or SRE (like irregex or irregex-search below) - it ensures the result is an SRE.

glob->sre

[procedure] (glob->sre <str>)

Converts a basic shell-style glob to an SRE which matches only strings which the glob would match. The glob characters [, ] * and ? are supported.

irregex?

[procedure] (irregex? <obj>)

Returns #t iff the object is a regular expression.

[procedure] (irregex-search <irx> <str> [<start> <end>])

Searches for any instances of the pattern <irx> (a POSIX string, SRE sexp, or pre-compiled regular expression) in <str>, optionally between the given range. If a match is found, returns a match object, otherwise returns #f.

Match objects can be used to query the original range of the string or its submatches using the irregex-match-* procedures below.

Examples:

(irregex-search "foobar" "abcFOOBARdef") => #f

(irregex-search (irregex "foobar" 'i) "abcFOOBARdef") => #<match>

(irregex-search '(w/nocase "foobar") "abcFOOBARdef") => #<match>

Note, the actual match result is represented by a vector in the default implementation. Throughout this manual, we'll just write #<match> to show that a successful match was returned when the details are not important.

Matching follows the POSIX leftmost, longest semantics, when searching. That is, of all possible matches in the string, irregex-search will return the match at the first position (leftmost). If multiple matches are possible from that same first position, the longest match is returned.

irregex-match

irregex-match?

[procedure] (irregex-match <irx> <str> [<start> <end>])
[procedure] (irregex-match? <irx> <str> [<start> <end>])

Like irregex-search, but performs an anchored match against the beginning and end of the substring specified by <start> and <end>, without searching.

Where irregex-match returns a match object, irregex-match? just returns a boolean indicating whether it matched or not.

Examples:

(irregex-match '(w/nocase "foobar") "abcFOOBARdef") => #f

(irregex-match '(w/nocase "foobar") "FOOBAR") => #<match>

irregex-match-data?

[procedure] (irregex-match-data? <obj>)

Returns #t iff the object is a successful match result from irregex-search or irregex-match.

irregex-num-submatches

irregex-match-num-submatches

[procedure] (irregex-num-submatches <irx>)
[procedure] (irregex-match-num-submatches <match>)

Returns the number of numbered submatches that are defined in the irregex or match object.

irregex-names

irregex-match-names

[procedure] (irregex-names <irx>)
[procedure] (irregex-match-names <match>)

Returns an association list of named submatches that are defined in the irregex or match object. The car of each item in this list is the name of a submatch, the cdr of each item is the numerical submatch corresponding to this name. If a named submatch occurs multiple times in the irregex, it will also occur multiple times in this list.

irregex-match-valid-index?

[procedure] (irregex-match-valid-index? <match> <index-or-name>)

Returns #t iff the index-or-name named submatch or index is defined in the match object.

irregex-match-substring

irregex-match-start-index

irregex-match-end-index

[procedure] (irregex-match-substring <match> [<index-or-name>])
[procedure] (irregex-match-start-index <match> [<index-or-name>])
[procedure] (irregex-match-end-index <match> [<index-or-name>])

Fetches the matched substring (or its start or end offset) at the given submatch index, or named submatch. The entire match is index 0, the first 1, etc. The default is index 0.

Returns #f if the given submatch did not match the source string (can happen when you have the submatch inside an or alternative, for example).

irregex-match-subchunk

irregex-match-start-chunk

irregex-match-end-chunk

[procedure] (irregex-match-subchunk <match> [<index-or-name>])
[procedure] (irregex-match-start-chunk <match> [<index-or-name>])
[procedure] (irregex-match-end-chunk <match> [<index-or-name>])

Access the chunks delimiting the submatch index, or named submatch.

irregex-match-subchunk generates a chunked data-type for the given match item, of the same type as the underlying chunk type (see Chunked String Matching below). This is only available if the chunk type specifies the get-subchunk API, otherwise an error is raised.

Returns #f if the given submatch did not match the source string (can happen when you have the submatch inside an or alternative, for example).

irregex-replace

irregex-replace/all

[procedure] (irregex-replace <irx> <str> [<replacements> ...])
[procedure] (irregex-replace/all <irx> <str> [<replacements> ...])

Matches a pattern in a string, and replaces it with a (possibly empty) list of substitutions. Each <replacement> can be either a string literal, a numeric index, a symbol (as a named submatch), or a procedure which takes one argument (the match object) and returns a string.

Examples:

(irregex-replace "[aeiou]" "hello world" "*") => "h*llo world"

(irregex-replace/all "[aeiou]" "hello world" "*") => "h*ll* w*rld"

(irregex-replace/all '(* "foo ") "foo foo platter" "*") => "**p*l*a*t*t*e*r"

(irregex-replace "(.)(.)" "ab" 2 1 "*")  => "ba*"

(irregex-replace "...bar" "xxfoobar" (lambda (m) 
              (string-reverse (irregex-match-substring m)))) => "xxraboof"

(irregex-replace "(...)(bar)" "xxfoobar"  2 (lambda (m) 
              (string-reverse (irregex-match-substring m 1)))) => "xxbaroof"

irregex-split

irregex-extract

[procedure] (irregex-split <irx> <str> [<start> <end>])
[procedure] (irregex-extract <irx> <str> [<start> <end>])

irregex-split splits the string <str> into substrings divided by the pattern in <irx>. irregex-extract does the opposite, returning a list of each instance of the pattern matched disregarding the substrings in between.

Empty matches will result in subsequent single character string in irregex-split, or empty strings in irregex-extract.

(irregex-split "[aeiou]*" "foobarbaz") => '("f" "b" "r" "b" "z")

(irregex-extract "[aeiou]*" "foobarbaz") => '("" "oo" "" "a" "" "" "a" "")

irregex-fold

[procedure] (irregex-fold <irx> <kons> <knil> <str> [<finish> <start> <end>])

This performs a fold operation over every non-overlapping place <irx> occurs in the string str.

The <kons> procedure takes the following signature:

(<kons> <from-index> <match> <seed>)

where <from-index> is the index from where we started searching (initially <start> and thereafter the end index of the last match), <match> is the resulting match-data object, and <seed> is the accumulated fold result starting with <knil>.

The rationale for providing the <from-index> (which is not provided in the SCSH regexp-fold utility), is because this information is useful (e.g. for extracting the unmatched portion of the string before the current match, as needed in irregex-replace/all), and not otherwise directly accessible.

Note when the pattern matches an empty string, to avoid an infinite loop we continue from one char after the end of the match (as opposed to the end in the normal case). The <from-index> passed to the subsequent \scheme{<kons>} or <finish> still refers to the original previous match end, however, so irregex-split and irregex-replace/all, etc. do the right thing.

The optional <finish> takes two arguments:

(<finish> <from-index> <seed>)

which simiarly allows you to pick up the unmatched tail of the string, and defaults to just returning the <seed>.

<start> and <end> are numeric indices letting you specify the boundaries of the string on which you want to fold.

To extract all instances of a match out of a string, you can use

(map irregex-match-substring
     (irregex-fold <irx>
                   (lambda (i m s) (cons m s))
		   '()
		   <str>
		   (lambda (i s) (reverse s))))

Note if an empty match is found <kons> will be called on that empty string, and to avoid an infinite loop matching will resume at the next char. It is up to the programmer to do something sensible with the skipped char in this case.

Extended SRE Syntax

Irregex provides the first native implementation of SREs (Scheme Regular Expressions), and includes many extensions necessary both for minimal POSIX compatibility, as well as for modern extensions found in libraries such as PCRE.

The following table summarizes the SRE syntax, with detailed explanations following.

 ;; basic patterns
 <string>                          ; literal string
 (seq <sre> ...)                   ; sequence
 (: <sre> ...)
 (or <sre> ...)                    ; alternation
 
 ;; optional/multiple patterns
 (? <sre> ...)                     ; 0 or 1 matches
 (* <sre> ...)                     ; 0 or more matches
 (+ <sre> ...)                     ; 1 or more matches
 (= <n> <sre> ...)                 ; exactly <n> matches
 (>= <n> <sre> ...)                ; <n> or more matches
 (** <from> <to> <sre> ...)        ; <n> to <m> matches
 (?? <sre> ...)                    ; non-greedy (non-greedy) pattern: (0 or 1)
 (*? <sre> ...)                    ; non-greedy kleene star
 (**? <from> <to> <sre> ...)       ; non-greedy range
 
 ;; submatch patterns
 (submatch <sre> ...)              ; numbered submatch
 ($ <sre> ...)
 (submatch-named <name> <sre> ...) ; named submatch
 (=> <name> <sre> ...)
 (backref <n-or-name>)             ; match a previous submatch
 
 ;; toggling case-sensitivity
 (w/case <sre> ...)                ; enclosed <sre>s are case-sensitive
 (w/nocase <sre> ...)              ; enclosed <sre>s are case-insensitive
 
 ;; character sets
 <char>                            ; singleton char set
 (<string>)                        ; set of chars
 (or <cset-sre> ...)               ; set union
 (~ <cset-sre> ...)                ; set complement (i.e. [^...])
 (- <cset-sre> ...)                ; set difference
 (& <cset-sre> ...)                ; set intersection
 (/ <range-spec> ...)              ; pairs of chars as ranges
 
 ;; named character sets
 any
 nonl
 ascii
 lower-case     lower
 upper-case     upper
 alphabetic     alpha
 numeric        num
 alphanumeric   alphanum  alnum
 punctuation    punct
 graphic        graph
 whitespace     white     space
 printing       print
 control        cntrl
 hex-digit      xdigit
 
 ;; assertions and conditionals
 bos eos                           ; beginning/end of string
 bol eol                           ; beginning/end of line
 bow eow                           ; beginning/end of word
 nwb                               ; non-word-boundary
 (look-ahead <sre> ...)            ; zero-width look-ahead assertion
 (look-behind <sre> ...)           ; zero-width look-behind assertion
 (neg-look-ahead <sre> ...)        ; zero-width negative look-ahead assertion
 (neg-look-behind <sre> ...)       ; zero-width negative look-behind assertion
 (atomic <sre> ...)                ; for (?>...) independent patterns
 (if <test> <pass> [<fail>])       ; conditional patterns
 commit                            ; don't backtrack beyond this (i.e. cut)
 
 ;; backwards compatibility
 (posix-string <string>)           ; embed a POSIX string literal

Basic SRE Patterns

The simplest SRE is a literal string, which matches that string exactly.

(irregex-search "needle" "hayneedlehay") => #<match>

By default the match is case-sensitive, though you can control this either with the compiler flags or local overrides:

(irregex-search "needle" "haynEEdlehay") => #f

(irregex-search (irregex "needle" 'i) "haynEEdlehay") => #<match>

(irregex-search '(w/nocase "needle") "haynEEdlehay") => #<match>

You can use w/case to switch back to case-sensitivity inside a w/nocase or when the SRE was compiled with 'i:

(irregex-search '(w/nocase "SMALL" (w/case "BIG")) "smallBIGsmall") => #<match>

(irregex-search '(w/nocase "small" (w/case "big")) "smallBIGsmall") => #f

Important: characters outside the ASCII range (ie, UTF8 chars) are not matched case insensitively!

Of course, literal strings by themselves aren't very interesting regular expressions, so we want to be able to compose them. The most basic way to do this is with the seq operator (or its abbreviation :), which matches one or more patterns consecutively:

(irregex-search '(: "one" space "two" space "three") "one two three") => #<match>

As you may have noticed above, the w/case and w/nocase operators allowed multiple SREs in a sequence - other operators that take any number of arguments (e.g. the repetition operators below) allow such implicit sequences.

To match any one of a set of patterns use the or alternation operator:

(irregex-search '(or "eeney" "meeney" "miney") "meeney") => #<match>

(irregex-search '(or "eeney" "meeney" "miney") "moe") => #f

SRE Repetition Patterns

There are also several ways to control the number of times a pattern is matched. The simplest of these is ? which just optionally matches the pattern:

(irregex-search '(: "match" (? "es") "!") "matches!") => #<match>

(irregex-search '(: "match" (? "es") "!") "match!") => #<match>

(irregex-search '(: "match" (? "es") "!") "matche!") => #f

To optionally match any number of times, use *, the Kleene star:

(irregex-search '(: "<" (* (~ #\>)) ">") "<html>") => #<match>

(irregex-search '(: "<" (* (~ #\>)) ">") "<>") => #<match>

(irregex-search '(: "<" (* (~ #\>)) ">") "<html") => #f

Often you want to match any number of times, but at least one time is required, and for that you use +:

(irregex-search '(: "<" (+ (~ #\>)) ">") "<html>") => #<match>

(irregex-search '(: "<" (+ (~ #\>)) ">") "<a>") => #<match>

(irregex-search '(: "<" (+ (~ #\>)) ">") "<>") => #f

More generally, to match at least a given number of times, use >=:

(irregex-search '(: "<" (>= 3 (~ #\>)) ">") "<table>") => #<match>

(irregex-search '(: "<" (>= 3 (~ #\>)) ">") "<pre>") => #<match>

(irregex-search '(: "<" (>= 3 (~ #\>)) ">") "<tr>") => #f

To match a specific number of times exactly, use =:

(irregex-search '(: "<" (= 4 (~ #\>)) ">") "<html>") => #<match>

(irregex-search '(: "<" (= 4 (~ #\>)) ">") "<table>") => #f

And finally, the most general form is ** which specifies a range of times to match. All of the earlier forms are special cases of this.

(irregex-search '(: (= 3 (** 1 3 numeric) ".") (** 1 3 numeric)) "192.168.1.10") => #<match>

(irregex-search '(: (= 3 (** 1 3 numeric) ".") (** 1 3 numeric)) "192.0168.1.10") => #f

There are also so-called "non-greedy" variants of these repetition operators, by convention suffixed with an additional ?. Since the normal repetition patterns can match any of the allotted repetition range, these operators will match a string if and only if the normal versions matched. However, when the endpoints of which submatch matched where are taken into account (specifically, all matches when using irregex-search since the endpoints of the match itself matter), the use of a non-greedy repetition can change the result.

So, whereas ? can be thought to mean "match or don't match," ?? means "don't match or match." * typically consumes as much as possible, but *? tries first to match zero times, and only consumes one at a time if that fails. If you have a greedy operator followed by a non-greedy operator in the same pattern, they can produce surprisins results as they compete to make the match longer or shorter. If this seems confusing, that's because it is. Non-greedy repetitions are defined only in terms of the specific backtracking algorithm used to implement them, which for compatibility purposes always means the Perl algorithm. Thus, when using these patterns you force IrRegex to use a backtracking engine, and can't rely on efficient execution.

SRE Character Sets

Perhaps more common than matching specific strings is matching any of a set of characters. You can use the or alternation pattern on a list of single-character strings to simulate a character set, but this is too clumsy for everyday use so SRE syntax allows a number of shortcuts.

A single character matches that character literally, a trivial character class. More conveniently, a list holding a single element which is a string refers to the character set composed of every character in the string.

(irregex-match '(* #\-) "---") => #<match>

(irregex-match '(* #\-) "-_-") => #f

(irregex-match '(* ("aeiou")) "oui") => #<match>

(irregex-match '(* ("aeiou")) "ouais") => #f

Ranges are introduced with the / operator. Any strings or characters in the / are flattened and then taken in pairs to represent the start and end points, inclusive, of character ranges.

(irregex-match '(* (/ "AZ09")) "R2D2") => #<match>

(irregex-match '(* (/ "AZ09")) "C-3PO") => #f

In addition, a number of set algebra operations are provided. or, of course, has the same meaning, but when all the options are character sets it can be thought of as the set union operator. This is further extended by the & set intersection, - set difference, and ~ set complement operators.

(irregex-match '(* (& (/ "az") (~ ("aeiou")))) "xyzzy") => #<match>

(irregex-match '(* (& (/ "az") (~ ("aeiou")))) "vowels") => #f

(irregex-match '(* (- (/ "az") ("aeiou"))) "xyzzy") => #<match>

(irregex-match '(* (- (/ "az") ("aeiou"))) "vowels") => #f

SRE Assertion Patterns

There are a number of times it can be useful to assert something about the area around a pattern without explicitly making it part of the pattern. The most common cases are specifically anchoring some pattern to the beginning or end of a word or line or even the whole string. For example, to match on the end of a word:

(irregex-search '(: "foo" eow) "foo") => #<match>

(irregex-search '(: "foo" eow) "foo!") => #<match>

(irregex-search '(: "foo" eow) "foof") => #f

The bow, bol, eol, bos and eos work similarly. nwb asserts that you are not in a word-boundary - if replaced for eow in the above examples it would reverse all the results.

There is no wb, since you tend to know from context whether it would be the beginning or end of a word, but if you need it you can always use (or bow eow).

Somewhat more generally, Perl introduced positive and negative look-ahead and look-behind patterns. Perl look-behind patterns are limited to a fixed length, however the IrRegex versions have no such limit.

(irregex-search '(: "regular" (look-ahead " expression"))
                "regular expression")
 => #<match>

The most general case, of course, would be an and pattern to complement the or pattern - all the patterns must match or the whole pattern fails. This may be provided in a future release, although it (and look-ahead and look-behind assertions) are unlikely to be compiled efficiently.

SRE Utility Patterns

The following utility regular expressions are also provided for common patterns that people are eternally reinventing. They are not necessarily the official patterns matching the RFC definitions of the given data, because of the way that such patterns tend to be used. There are three general usages for regexps:

searching
search for a pattern matching a desired object in a larger text
validation
determine whether an entire string matches a pattern
extraction
given a string already known to be valid, extract certain fields from it as submatches

In some cases, but not always, these will overlap. When they are different, irregex-search will naturally always want the searching version, so IrRegex provides that version.

As an example where these might be different, consider a URL. If you want to match all the URLs in some arbitrary text, you probably want to exclude a period or comma at the tail end of a URL, since it's more likely being used as punctuation rather than part of the URL, despite the fact that it would be valid URL syntax.

Another problem with the RFC definitions is the standard itself may have become irrelevant. For example, the pattern IrRegex provides for email addresses doesn't match quoted local parts (e.g. "first last"@domain.com) because these are increasingly rare, and unsupported by enough software that it's better to discourage their use. Conversely, technically consecutive periods (e.g. first..last@domain.com) are not allowed in email addresses, but most email software does allow this, and in fact such addresses are quite common in Japan.

The current patterns provided are:

 newline                        ; general newline pattern (crlf, cr, lf)
 integer                        ; an integer
 real                           ; a real number (including scientific)
 string                         ; a "quoted" string
 symbol                         ; an R5RS Scheme symbol
 ipv4-address                   ; a numeric decimal ipv4 address
 ipv6-address                   ; a numeric hexadecimal ipv6 address
 domain                         ; a domain name
 email                          ; an email address
 http-url                       ; a URL beginning with https?://

Because of these issues the exact definitions of these patterns are subject to be changed, but will be documented clearly when they are finalized. More common patterns are also planned, but as what you want increases in complexity it's probably better to use a real parser.

Supported PCRE Syntax

Since the PCRE syntax is so overwhelming complex, it's easier to just list what we *don't* support for now. Refer to the PCRE documentation for details. You should be using the SRE syntax anyway!

Unicode character classes (\P) are not supported, but will be in an upcoming release. \C named characters are not supported.

Callbacks, subroutine patterns and recursive patterns are not supported. (*FOO) patterns are not supported and may never be.

\G and \K are not supported.

Octal character escapes are not supported because they are ambiguous with back-references - just use hex character escapes.

Other than that everything should work, including named submatches, zero-width assertions, conditional patterns, etc.

In addition, \< and \> act as beginning-of-word and end-of-word marks, respectively, as in Emacs regular expressions.

Also, two escapes are provided to embed SRE patterns inside PCRE strings, "\'<sre>" and "(*'<sre>)". For example, to match a comma-delimited list of integers you could use

"\\'integer(,\\'integer)*"

and to match a URL in angle brackets you could use

"<('*http-url)>"

Note in the second example the enclosing "('*...)" syntax is needed because the Scheme reader would consider the closing ">" as part of the SRE symbol.

The following chart gives a quick reference from PCRE form to the SRE equivalent:

 ;; basic syntax
 "^"                     ;; bos (or eos inside (?m: ...))
 "$"                     ;; eos (or eos inside (?m: ...))
 "."                     ;; nonl
 "a?"                    ;; (? a)
 "a*"                    ;; (* a)
 "a+"                    ;; (+ a)
 "a??"                   ;; (?? a)
 "a*?"                   ;; (*? a)
 "a+?"                   ;; (+? a)
 "a{n,m}"                ;; (** n m a)
 ;; grouping
 "(...)"                 ;; (submatch ...)
 "(?:...)"               ;; (: ...)
 "(?i:...)"              ;; (w/nocase ...)
 "(?-i:...)"             ;; (w/case ...)
 "(?<name>...)"          ;; (=> <name>...)
 ;; character classes
 "[aeiou]"               ;; ("aeiou")
 "[^aeiou]"              ;; (~ "aeiou")
 "[a-z]"                 ;; (/ "az") or (/ "a" "z")
 "[[:alpha:]]"           ;; alpha
 ;; assertions
 "(?=...)"               ;; (look-ahead ...)
 "(?!...)"               ;; (neg-look-ahead ...)
 "(?<=...)"              ;; (look-behind ...)
 "(?<!...)"              ;; (neg-look-behind ...)
 "(?(test)pass|fail)"    ;; (if test pass fail)
 "(*COMMIT)"             ;; commit

Chunked String Matching

It's often desirable to perform regular expression matching over sequences of characters not represented as a single string. The most obvious example is a text-buffer data structure, but you may also want to match over lists or trees of strings (i.e. ropes), over only certain ranges within a string, over an input port, etc. With existing regular expression libraries, the only way to accomplish this is by converting the abstract sequence into a freshly allocated string. This can be expensive, or even impossible if the object is a text-buffer opened onto a 500MB file.

IrRegex provides a chunked string API specifically for this purpose. You define a chunking API with make-irregex-chunker:

make-irregex-chunker

[procedure] (make-irregex-chunker <get-next> <get-string> [<get-start> <get-end> <get-substring> <get-subchunk>])

where

(<get-next> chunk) => returns the next chunk, or #f if there are no more chunks

(<get-string> chunk) => a string source for the chunk

(<get-start> chunk) => the start index of the result of <get-string> (defaults to always 0)

(<get-end> chunk) => the end (exclusive) of the string (defaults to string-length of the source string)

(<get-substring> cnk1 i cnk2 j) => a substring for the range between the chunk cnk1 starting at index i and ending at cnk2 at index j

(<get-subchunk> cnk1 i cnk2 j) => as above but returns a new chunked data type instead of a string (optional)

There are two important constraints on the <get-next> procedure. It must return an eq? identical object when called multiple times on the same chunk, and it must not return a chunk with an empty string (start == end). This second constraint is for performance reasons - we push the work of possibly filtering empty chunks to the chunker since there are many chunk types for which empty strings aren't possible, and this work is thus not needed. Note that the initial chunk passed to match on is allowed to be empty.

<get-substring> is provided for possible performance improvements - without it a default is used. <get-subchunk> is optional - without it you may not use irregex-match-subchunk described above.

You can then match chunks of these types with the following procedures:

irregex-search/chunked

irregex-match/chunked

[procedure] (irregex-search/chunked <irx> <chunker> <chunk> [<start>])
[procedure] (irregex-match/chunked <irx> <chunker> <chunk> [<start>])

These return normal match-data objects.

Example:

To match against a simple, flat list of strings use:

  (define (rope->string rope1 start rope2 end)
    (if (eq? rope1 rope2)
        (substring (car rope1) start end)
        (let loop ((rope (cdr rope1))
                   (res (list (substring (car rope1) start))))
           (if (eq? rope rope2)
               (string-concatenate-reverse      ; from SRFI-13
                (cons (substring (car rope) 0 end) res))
               (loop (cdr rope) (cons (car rope) res))))))

  (define rope-chunker
    (make-irregex-chunker (lambda (x) (and (pair? (cdr x)) (cdr x)))
                          car
                          (lambda (x) 0)
                          (lambda (x) (string-length (car x)))
                          rope->string))

  (irregex-search/chunked <pat> rope-chunker <list-of-strings>)

Here we are just using the default start, end and substring behaviors, so the above chunker could simply be defined as:

  (define rope-chunker
    (make-irregex-chunker (lambda (x) (and (pair? (cdr x)) (cdr x))) car))

irregex-fold/chunked

[procedure] (irregex-fold/chunked <irx> <kons> <knil> <chunker> <chunk> [<finish> [<start-index>]])

Chunked version of irregex-fold.

Utilities

The following procedures are also available.

irregex-quote

[procedure] (irregex-quote <str>)

Returns a new string with any special regular expression characters escaped, to match the original string literally in POSIX regular expressions.

irregex-opt

[procedure] (irregex-opt <list-of-strings>)

Returns an optimized SRE matching any of the literal strings in the list, like Emacs' regexp-opt. Note this optimization doesn't help when irregex is able to build a DFA.

sre->string

[procedure] (sre->string <sre>)

Convert an SRE to a PCRE-style regular expression string, if possible.


Previous: Module (chicken io)

Next: Module (chicken keyword)